<template>
    <div class='mainContent planAdd'>
        <div class="scorll">
            <div class="content">
                <div class="search" style="padding:0.15rem 2%;">
                    <div class="toBack" @click="$router.push({ path: '/fmam/plan' })" plain> <span class="el-icon-arrow-left">返回</span></div>
                    <el-button type="primary" @click="addRowFn" plain v-if='btnList.includes("fmam/plan/add")'>+ 添加材料</el-button>
                    <div class="line"></div>
                </div>
                <div class="inputName">
                    <div class="item">
                        <span class="tip">*</span>
                        <span>计划名称：</span>
                        <Input v-model="name" placeholder="请输入计划名称" show-word-limit :maxlength="maxlength" style="flex:1;" clearable />
                        <input type="password" autocomplete="new-password" style="display: none" />
                    </div>
                    <div class="item">
                        <span>计划编码：</span>
                        <Input v-model="code" placeholder="请输入计划编码" show-word-limit :maxlength="maxlength" style="flex:1;" clearable />
                        <input type="password" autocomplete="new-password" style="display: none" />
                    </div>
                    <div class="upload">
                        <span>附件：</span>
                        <el-upload
                            class="avatar-uploader"
                            :headers="headers"
                            :action="$axios.defaults.baseURL+'/ms/api/fmam/plan/file/upload'"
                            :show-file-list="false"
                            :on-success="uploadSuccess"
                            accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG,.doc,.xls,.xlsx"
                            :before-upload="beforeAvatarUpload">
                            <img v-if="fileType == 1 && fileUrl" :src="exelIcon" class="avatar" />
                            <img v-if="fileType == 2 && fileUrl" :src="fileUrl" class="avatar" />
                            <img v-if="fileType == 3 && fileUrl" :src="wordIcon" class="avatar" />
                            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                        </el-upload>
                    </div>
                </div>
                <div class="tabBox" style="border-radius:0;border-bottom-left-radius: 10px;border-bottom-right-radius: 10px;">
                    <div class="tableList" ref="tableList">
                        <el-table :data="matList" style="width: 100%" :height="tableOffsetTop" :stripe="true">
                            <template slot="empty">
                                <div class="no_lsit" style="width:96%;margin:auto;">
                                    <img src="./../../assets/images/common/rotary_nodata.png" />
                                </div>
                            </template>
                            <el-table-column prop="matName" label="名称 | 编码" align="center" width='250px'>
                                <template slot-scope="scope">
                                    <el-button type="text" size="small" style="color:RGBA(64, 158, 255, 1);">{{scope.row.matName}}{{scope.row.matCode ? '(' + scope.row.matCode + ')' :''}}</el-button>
                                </template>
                            </el-table-column>
                            <el-table-column prop="spec" label="规格型号" align="center" width='100px'>
                                <template slot-scope="scope">
                                    {{scope.row.spec ? scope.row.spec : '—'}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="unitName" label="单位" align="center" width='100px'>
                                <template slot-scope="scope">
                                    {{scope.row.unitName ? scope.row.unitName : '—'}}
                                </template>
                            </el-table-column>
                            <el-table-column prop="number" label="数量" align="center">
                                <template slot="header">
                                    <span style="color:Red;">*</span>
                                    <span>数量</span>
                                </template>
                                <template slot-scope="scope">
                                    <InputNumber v-model="scope.row.number" :min="0" :max="9999" style="width:150px;"></InputNumber>
                                    <input type="password" autocomplete="new-password" style="display: none" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="useTime" label="计划进场时间" align="center">
                                <template slot-scope="scope">
                                    <DatePicker type="date" :editable='false' :clearable='false' :options="options" placeholder="请选择结束日期" style="width: 150px" format="yyyy-MM-dd" v-model="scope.row.useTime" ></DatePicker>
                                    <input type="password" autocomplete="new-password" style="display: none" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="usePart" label="计划使用部位" align="center">
                                <template slot-scope="scope">
                                    <Input v-model="scope.row.usePart" placeholder="请输入" show-word-limit :maxlength="maxlength" style="width: 150px" clearable />
                                    <input type="password" autocomplete="new-password" style="display: none" />
                                </template>
                            </el-table-column>
                            <el-table-column prop="remark" label="备注" align="center">
                                <template slot-scope="scope">
                                    <Input v-model="scope.row.remark" placeholder="请输入" show-word-limit :maxlength="maxlength" style="width: 150px" clearable />
                                    <input type="password" autocomplete="new-password" style="display: none" />
                                </template>
                            </el-table-column>
                            <el-table-column  label="操作" align="center"  width='100px'>
                                <template slot-scope="scope">
                                    <el-button style="color:red" @click.native.prevent="removeFn(scope.$index)" type="text" size="small">删除</el-button>
                                </template>
                            </el-table-column>
                        </el-table>
                    </div>
                </div>
                <div class="submitBtn">
                    <el-button type="primary" @click="cancel(2)" plain style="margin-right:0.5rem;">取消计划</el-button>
                    <el-button type="primary" @click="submitFn" plain>提交计划</el-button>
                </div>
            </div>
        </div>
        <Modal v-model="modal" title="添加材料" width="1300px;" :mask-closable="false">
            <div class="planModal">
                <div class="left">
                    <h2 class="h2">
                        <span class="bc"></span>
                        <span>材料类别</span>
                    </h2>
                    <div class="scorll">
                        <el-tree :data="treeList"  ref="treeBox" @node-click="handleNodeClick"  node-key="id" :render-content="renderContent" :expand-on-click-node="false" :highlight-current="true" :filter-node-method="filterNode" :default-expanded-keys="[checkId]"></el-tree>
                    </div>
                </div>
                <div class="center">
                    <h2 class="h2">
                        <span class="bc"></span>
                        <span>材料明细</span>
                    </h2>
                    <div class="tabBox">
                        <div class="tableList">
                            <el-table :data="detailList" style="width: 100%" height="400px" :stripe="true" @row-click="setSelectedLisFn">
                                <template slot="empty">
                                    <div class="no_lsit" style="width:96%;margin:auto;">
                                        <img src="./../../assets/images/common/rotary_nodata.png" />
                                    </div>
                                </template>
                                <el-table-column prop="machCode" label="名称 | 编码" align="left" width='200px'>
                                    <template slot-scope="scope">
                                       <p style="text-align:left;">编码：{{scope.row.fullCode ? scope.row.fullCode : '—'}}</p>
                                       <p style="text-align:left;">名称：{{scope.row.name ? scope.row.name : '—'}}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="machCode" label="规格型号 | 材质" align="left" width='200px'>
                                    <template slot-scope="scope">
                                       <p>规格型号：{{scope.row.spec ? scope.row.spec : '—'}}</p>
                                       <p>材质：{{scope.row.texture ? scope.row.texture : '—'}}</p>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="unitName" label="单位" align="center"> </el-table-column>
                            </el-table>
                        </div>
                        <div class="clearfix" v-show="detailList.length > 0" >
                            <div class="float-right">
                                <Page v-if="totalCount" style="margin: 20px 0;text-align: center;" :current.sync="current" :total="totalCount" :page-size="pageSize" show-elevator show-total @on-change="pageChange"></Page>
                            </div>
                        </div>
                    </div>
                </div>
                <div class="right">
                    <h2 class="h2">
                        <span class="bc"></span>
                        <span>已选材料</span>
                    </h2>
                    <div class="list">
                        <div class="item" v-for=" (item , index) in selectedList" :key="index">
                            {{item.name}} {{item.fullCode ? '(' + item.fullCode +')' :''}}
                            <img src="../../assets/images/fmam/plan/rule_del.png" class="delImg" @click="removeFn(index)" v-if="item.flag" />
                        </div>
                    </div>
                </div>
            </div>
            <div slot="footer">
                <el-button @click="cancel(1)" type="info" size="small" plain>取消</el-button>
                <el-button @click="submit" type="primary" size="small" plain >确定</el-button>
            </div>
        </Modal>
    </div>
</template>

<script>
import {getMatTypelist,getMatList} from '@/api/api';
import {getFmamPlanAdd,getFmamPlanEdit,getFmamPlanDetail} from '@/api/fmam';
import {trans, uniqObjInArray} from '@/sever/config';
import {filterRepeat,initYMD} from '@/sever/utils';

export default {
    data () {
        return {
            headers: {
                Authorization:localStorage.getItem('COOKIE'),
            },
            options: {
                disabledDate(date) {
                    return date > Date.now();
                }
            },
            btnList:[],
            treeList:[],
            matList:[],
            detailList:[],
            selectedList:[],
            maxlength:25,
            limitlength:32,
            name:'',
            code:'',
            deptId:"",
            deptName:"",
            checkId:"",
            totalCount:0,
            pageNum:1,
            pageSize:5,
            current:1,
            matId:'',
            fileUrl:'',
            tableOffsetTop:0,
            modal:false,
            planId:'',
            state:'',
            fileType:'',
            exelIcon: require("./../../assets/images/fmam/plan/fmam_exel.png"),
            wordIcon: require("./../../assets/images/fmam/plan/fmam_word.png"),

        }
    },
    computed: {
        porjectObject() {
            return this.$store.state.porjectObject;
        },
    },
    watch: {
        porjectObject(val, oldVal) {
            if (val.deptId != oldVal.deptId) {
                this.deptId = val.deptId;
                this.getMatType();
                let queryObj = this.$route.query;
                if(queryObj.planId){
                    this.planId = queryObj.planId;
                    this.getFmamPlanDetailFn();
                }
            }
        },
    },
    methods: {
        // 请求计划充填数据
        getFmamPlanDetailFn() {
            let params = {
                planId:this.planId
            };
            getFmamPlanDetail(params)
                .then(res => {
                    if (res.code == 200) {
                        let matList = res.data.matList;
                        this.name = res.data.name;
                        this.code = res.data.code;
                        this.fileUrl = res.data.fileUrl;
                        this.state = res.data.state;
                        this.matList =[];
                        this.selectedList =[];
                        matList.forEach(v => {
                            this.matList.push(v)
                            let obj = {
                                id : v.matId,
                                fullCode : v.matCode,
                                name : v.matName,
                                spec : v.spec,
                                model : v.model,
                                texture : v.texture,
                                unitId : v.unitId,
                                unitName : v.unitName,
                                flag : true
                            };
                            this.selectedList.push(obj);
                        })
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        // 请求材料类型
        getMatType() {
            let params = {
                deptId: this.deptId
            };
            getMatTypelist(params)
                .then(res => {
                    if (res.code == 200) {
                        let list = res.data.list;
                        if(list.length > 0 ){
                            this.checkId = list[0].id;
                            this.treeList = trans(list);
                        }
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        // 请求材料明细
        getFmamDetailsFn(){
            this.detailList = [];
            let params = {
                matTypeId: this.matId,
                pageSize: this.pageSize,
            };
            getMatList(params, this.pageNum)
                .then(res => {
                    if (res.code == 200) {
                        if(res.data.list.length > 0 ){
                            let list = res.data.list;
                            list.forEach(v=>{
                                v.flag = false;
                            })
                            this.detailList = list;
                            this.totalCount = res.data.total;
                        }
                    } else {
                        this.$Message.warning(res.msg);
                    }
                })
                .catch(error => {
                    console.log(error);
                });
        },
        pageChange(index) {
            this.pageNum = index;
            this.getFmamDetailsFn();
        },
        addRowFn(){
            this.modal = true;
            this.matList.forEach(v=>{
                this.selectedList.forEach(item => {
                    if(v.matId == item.id){
                        item['number'] = v.number;
                        item['remark'] = v.remark;
                        item['usePart'] = v.usePart;
                    }
                })
            })
        },
        // 提交数据到表格
        submit(){
            if(this.selectedList.length == 0){
                this.$Modal.warning({
                    title: "您有必选字段",
                    content: "材料明细不能为空"
                });
                return;
            }
            this.matList = [];
            this.selectedList.forEach(v => {
                let obj = {
                    matId : v.id,
                    matCode : v.fullCode,
                    matName : v.name,
                    spec : v.spec,
                    model : v.model,
                    texture : v.texture,
                    unitId : v.unitId,
                    unitName : v.unitName,
                    useTime : new Date(),
                    usePart : v.usePart || '',
                    remark : v.remark ||  '',
                    number : v['number'] || 0,
                };
                this.matList.push(obj);
            });
            this.modal = false;
        },
        // 提交数据到数据库
        submitFn(){
            if(!this.name){
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "计划名称不能为空"
                });
                return;
            }
            let flag = true;
            if(this.matList.length == 0 ){
                flag = false;
            }
            this.matList.forEach(v => {
                v.useTime = initYMD(v.useTime);
                if(v.number <= 0){
                    flag = false;
                }
            })
            if(flag){
                if(!this.planId){
                    let params = {
                        deptId : this.deptId,
                        deptName : this.deptName,
                        name : this.name,
                        code : this.code,
                        fileUrl : this.fileUrl,
                        matList : this.matList,
                    }
                    getFmamPlanAdd(params)
                    .then(res => {
                        if (res.code == 200) {
                            this.$router.push({ path: '/fmam/plan' })
                            this.$Message.success("操作成功");
                        } else {
                            this.$Message.warning(res.msg);
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
                }else{
                    let params = {
                        planId:this.planId,
                        state:this.state,
                        deptId : this.deptId,
                        deptName : this.deptName,
                        name : this.name,
                        code : this.code,
                        fileUrl : this.fileUrl,
                        matList : this.matList,
                    }
                    getFmamPlanEdit(params)
                    .then(res => {
                        if (res.code == 200) {
                            this.$router.push({ path: '/fmam/plan' })
                            this.$Message.success("操作成功");
                        } else {
                            this.$Message.warning(res.msg);
                        }
                    })
                    .catch(error => {
                        console.log(error);
                    });
                }
            }else{
                this.$Modal.warning({
                    title: "您有必填字段",
                    content: "采购数量不能为空"
                });
            }
        },
        cancel(i){
            if(i == 1){
                this.modal = false;
            }else if(i == 2){
                this.matList = [];
                this.$router.push({ path: '/fmam/plan' })
            }
        },
        removeFn(index,rows,type) {
            this.matList.forEach((v,i)=>{
                if(i == index){
                    v['number'] = 0;
                    v['remark'] = '';
                    v['usePart'] = '';
                }
            })
            this.selectedList.forEach((v,i)=>{
                if(i == index){
                    v['number'] = 0;
                    v['remark'] = '';
                    v['usePart'] = '';
                }
            })
            this.matList.splice(index,1);
            this.selectedList.splice(index,1);
        },
        renderContent (h, { root, node, data }) {
            return (
               <span class="custom-tree-node">
                    <span class="title">{data.label}</span>
                </span>
            )
        },
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        //树节点点击事件
        handleNodeClick(data){
            console.log(data)
            this.matId = data.id;
            this.getFmamDetailsFn();
        },
        setSelectedLisFn(row) {
            let flag = true;
            let obj = row;
            this.selectedList.forEach(v=>{
                if(v.id == obj.id){
                    flag = false;
                }
            })
            if(flag){
                obj.flag = true;
                obj.number = 0;
                obj.remark = '';
                obj.usePart = '';
                this.selectedList.push(obj);
            }
        },
        uploadSuccess(res, file) {
            this.fileUrl = res.data.path;
            this.$Message.success("上传成功");
        },
        // 图片大小检查
        beforeAvatarUpload(file) {
            if(file.type == 'application/vnd.ms-excel'){
                this.fileType = 1;
            }else if(file.type == 'image/png' || file.type == 'image/jpg' || file.type == 'image/jpeg'){
                this.fileType = 2;
            }else if(file.type == 'application/msword'){
                this.fileType = 3;
            }
            const isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                this.$Message.error("上传文件不能超过 2MB!");
            }
            return;
        },
    },
    mounted(){
        this.deptId = this.$store.state.porjectObject.deptId;
        this.deptName = this.$store.state.porjectObject.name;
        this.btnList = JSON.parse(localStorage.getItem("arr"));
        this.getMatType();
        let queryObj = this.$route.query;
        if(queryObj.planId){
            this.planId = queryObj.planId;
            this.getFmamPlanDetailFn();
        }
        this.$nextTick(()=>{
            //在下次 DOM 更新循环结束之后执行这个回调。在修改数据之后立即使用这个方法，获取更新后的DOM.
            this.tableOffsetTop = window.innerHeight - (this.$refs.tableList.offsetTop + 100);
        })
    },
}
</script>

<style scoped lang="less">
@import "./../../assets/style/themeBase.less";
</style>

<style scoped lang='scss'>
@import "./../../assets/style/fmam/mainContent.scss";
@function pxToRem($val) {
    @return $val/100 + rem;
}
/deep/.planModal{
    width: 98%;
    height: 500px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;
    margin: auto;
    padding: 20px 0 ;
    box-sizing: border-box;
    .h2{
        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 15px;
        .bc{
            width: 5px;
            height: 15px;
            background: var(--themeColor);
            margin-right: 10px;
        }
    }
    .left{
        width: 25%;
        height: 100%;
        box-sizing: border-box;
        .scorll{
            width: 100%;
            overflow-y: auto;
            height: calc(100% - 10px);
            margin: auto;
            padding: 15px 5%;
            border-radius: 10px;
            border: 1px solid #eee;
            box-sizing: border-box;
        }
        .scorll::-webkit-scrollbar {
            width: 6px;
        }
        /*滚动槽*/
        .scorll::-webkit-scrollbar-track {
            -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
            box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
            border-radius: 10px;
        }
        /* 滚动条滑块 */
        .scorll::-webkit-scrollbar-thumb {
            border-radius: 10px;
            background: rgba(0, 0, 0, 0.1);
            -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
            box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
        }
        .scorll::-webkit-scrollbar-thumb:window-inactive {
            background: rgba(255, 0, 0, 0.4);
        }
    }
    .center{
        width: 50%;
        height: 480px;
        border-right: 1px solid #eee;
        border-left: 1px solid #eee;
        margin: 0 5px;
        padding: 0 5px;
        box-sizing: border-box;
    }
    .right{
        width: 35%;
        height: 100%;
        .list{
            width: 98%;
            overflow-y: auto;
            height: calc(100% - 10px);
            margin: auto;
            padding: 15px 5%;
            border-radius: 10px;
            border: 1px solid #eee;
            box-sizing: border-box;
            &::-webkit-scrollbar {
                width: 6px;
            }
            /*滚动槽*/
            &::-webkit-scrollbar-track {
                -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
                box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
                border-radius: 10px;
            }
            /* 滚动条滑块 */
            &::-webkit-scrollbar-thumb {
                border-radius: 10px;
                background: rgba(0, 0, 0, 0.1);
                -webkit-box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
                box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
            }
            &::-webkit-scrollbar-thumb:window-inactive {
                background: rgba(255, 0, 0, 0.4);
            }
            .item{
                position: relative;
                width: 100%;
                height: 60px;
                line-height: 60px;
                text-align: center;
                border-radius: 10px;
                border: 1px solid #eee;
                box-sizing: border-box;
                margin-bottom: 15px;
                .delImg{
                    position: absolute;
                    right: -10px;
                    top: -10px;
                    width: 20px;
                    height: 20px;
                    cursor: pointer;
                }
            }
        }
    }
    .tabBox{
        width:100%;
        margin:0 auto;
        .tableList{
            width: 96%;
            margin: auto;
            /deep/ .el-table{
                color: RGBA(96, 98, 102, 1);
                font-family: MicrosoftYaHei;
                font-size: pxToRem(14);
                td,
                th.is-leaf{
                    border-bottom: none;
                }
                tr{
                    border: none;
                }
                thead th{
                    background-color: RGBA(220, 235, 254, 1) !important;
                    color: RGBA(144, 147, 153, 1);
                    font-weight: 400;
                }
            }
            .el-table__empty-text{
                width: 100%;
                    .no_lsit {
                    margin: auto;
                    img{
                        width: 400px;
                        height: 300px !important;
                    }
                }
            }
            /deep/ .el-table__row{
                background-color: #fff;
                cursor: pointer;
            }
            /deep/ .el-table--striped .el-table__body tr.el-table__row--striped td{
                background-color: RGBA(220, 235, 254, 0.5) ;
                cursor: pointer;
            }
        }
    }
    /deep/.custom-tree-node{
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .title{
            display: inline-block;
            width: 100%;
            font-size: 14px;
            overflow: hidden;
            text-overflow:ellipsis;
            white-space: nowrap;
            margin-left: 5px;
        }
    }
}
/deep/ .upload{
    span{
        width: pxToRem(60);
    }
    display: flex;
    justify-content: flex-start;
    align-items: center;
    height: pxToRem(50);
    .avatar-uploader .el-upload {
        width: pxToRem(50);
        height: pxToRem(50);
        cursor: pointer;
        position: relative;
        overflow: hidden;
        border-radius: 5px;
        box-sizing: border-box;
        background-color: #EEEEEE !important;
    }
    .avatar-uploader .el-upload:hover {
        border-color: var(--themeColor);
    }
    .avatar-uploader-icon {
        font-size: pxToRem(28);
        color: #D2D2D2;
        width: pxToRem(50);
        height: pxToRem(50);
        line-height: pxToRem(50);
        text-align: center;
    }
    .avatar {
        width: pxToRem(50);
        height: pxToRem(50);
        display: block;
    }
}

</style>
